<template>
	<view>
		<view class="container">
			<!-- <headerView :title='title' :backBtn="true"></headerView> -->
			<cu-custom bgColor="bg-gradual-orange" :isBack="true">
				<block slot="content">会员商品</block>
			</cu-custom>
			<view class="content">
				<!-- <view class="order-user-info"> -->
				<view class="order-user-info" @click="chooseAddress">
					<image class="address-icon" src="https://app.yycjkb.cn/index/fujiajia/coordinates_fill.png">
					</image>
					<view class="user-info" v-if="form.name">
						<view class="user">
							<text class="name">{{ form.name }}</text>
							<text>{{ form.phone }}</text>
						</view>
						<view class="address">
							收货地址：<text> {{ form.detail }}</text>
						</view>
					</view>
					<!-- <view v-else>
						<view class="user" style="margin-left:5px;">选择收货地址</view>

					</view> -->
				</view>
			</view>

			<view class="order-info-one">
				<view class="tab-content-item">
					<view class="tab-center">
						<view class="shop-info">
							<image class="shop-info-image" :src="goodsInfo.thumb" mode=""></image>
							<view class="shop-info-content">
								<view class="info-content-title">
									<view class="">
										{{ goodsInfo.name  }}
									</view>
									<view class="">
										￥{{ goodsInfo.money }}
									</view>
								</view>
								<view class="info-content">
									<!-- <view class="">
										{{ goodsInfo.name }}
									</view> -->
									<view class="">
										X{{ goodsInfo.count }}
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- <view class="buy-count">
						<view class="count-title">
							购买数量
						</view>
						<view class="edit-count">
							<view class="minus" @click="decreaseQuantity">
								-
							</view>
							<view class="quantity">{{ quantity }}</view>
							<view class="plus" @click="increaseQuantity">
								+
							</view>
						</view>
					</view> -->
				</view>
			</view>

			<view class="order-info-two">
				<view class="order-info-content">
					<view class="item">
						<view class="">
							商品总价：
						</view>
						<view class="">￥{{ goodsInfo.money }}</view>
					</view>
					<!-- <view class="item">
						<view class="">
							运费：
						</view>
						<view class="">￥{{ shippingFee }}</view>
					</view>
					<view class="item">
						<view class="">
							手续费：
						</view>
						<view class="">￥{{ handlingFee }}</view>
					</view> -->
				</view>
				<view class="all-count">
					<view class="">共{{ goodsInfo.count }}件商品 合计：</view>
					<view class="price">
						￥{{ goodsInfo.money }}
					</view>
				</view>
			</view>
			<view class="order-info-two" v-if="form.payStatus !== 'paid'">
				<view class="padding-sm">
					<!-- 支付方式选项 -->
					<view class="pay-options">
						<radio-group @change="radioChange">
							<label v-for="payItem in items" :key="payItem.value" class="uni-list-cell uni-list-cell-pd">
								<view class="uni-list-cell-item" style="margin-top:10px">
									<radio :value="payItem.value" :checked="payItem.value === form.pay_type" />
									<text style="padding-left:10rpx;">{{ payItem.name }}</text>
								</view>
							</label>
						</radio-group>
					</view>
				</view>
			</view>

			<view class="login-form-btn" @click="openVip()" v-if="form.payStatus !== 'paid'">
				确认订单，去支付
			</view>
			<!-- 支付状态提示（仅当已支付时显示） -->
			<view class="order-status-box" v-else>
				<view class="status-content">
					<image src="https://example.com/success-icon.png" class="status-icon"></image>
					<text class="status-text">订单状态：已支付</text>
					<text class="status-tips">感谢您的购买，商品将尽快发出</text>
				</view>
			</view>

			<!-- 底部 tabbar -->
			<!-- <tabBar :selectIndex="selectIndex"></tabBar> -->
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	var wx = require('jweixin-module');
	// #endif

	// #ifdef APP
	import wx from 'weixin-js-sdk';
	// #endif

	const isWechat = () => {
		return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
	};

	import yhdslplace from "@/components/yhdsl-place/yhdsl-place.vue";
	import shop from "@/api/shop";
	import banlance from "@/api/banlance";
	import {
		mapActions,
		mapState
	} from "vuex";
	import headerView from "../../components/header/header.vue";
	import tabBar from "../../components/tabBar/index.vue";


	export default {
		components: {
			tabBar,
			headerView,
			yhdslplace
		},
		data() {
			return {
				orderInfo: {},

				title: "确认订单",
				selectIndex: 1,
				quantity: 1, // 商品数量
				shippingFee: 0, // 运费
				handlingFee: 0, // 手续费
				goodsInfo: {
					name: "",
					money: 0,
					thumb: "",
					count: 1,
				},
				form: {
					pay_type: 'wechat',
					name: "",
					phone: "",
					region: ['', '', ''],
					detail: "",
					orderSN: '', // 订单编号
					payStatus: 'unpaid'
				},
				id: 1, // 商品 ID
				items: [{
						name: "微信支付",
						value: '1' // 确保这是字符串
					},
					{
						name: "余额支付",
						value: '2' // 确保这是字符串
					}, {
						name: "银联支付",
						value: '3' // 确保这是字符串
					},
				],
			};
		},
		computed: {
			totalPrice() {
				return this.quantity * (this.goodsInfo.money || 0);
			},
			totalAmount() {
				return this.totalPrice + this.shippingFee + this.handlingFee;
			}
		},
		// async onLoad(options) {
		// 	// this.id = options.id || 1;
		// 	// await this.findGoodsInfo();
		// 	// this.getWechatCode()
		// },
		onLoad(options) {
			if (options.orderData) {
				const order = JSON.parse(decodeURIComponent(options.orderData));
				// console.log(JSON.stringify(order, null, 2)); // 美化输出
				this.form = {
					name: order.userName,
					phone: order.tel,
					detail: order.address,
					pay_type: order.pay_type,
					orderSN: order.orderSN,
					payStatus: order.payStatus,
				};
				this.goodsInfo = {
					name: order.productName,
					money: order.totalPrice,
					thumb: order.productImage,
					count: order.productCount,
				};
				this.quantity = 1;
				this.totalPrice = parseFloat(order.order_money);
				this.totalAmount = parseFloat(order.pay_price);
			}
		},
		// 监听页面返回的地址信息
		onShow() {
			const selectedAddress = uni.getStorageSync('selectedAddress'); // 读取存储的地址
			if (selectedAddress) {
				this.form.name = selectedAddress.name;
				this.form.phone = selectedAddress.tel; // 你的地址列表 `phone` 字段是 `tel`
				// this.form.region = [selectedAddress.province, selectedAddress.city, selectedAddress.district];
				this.form.detail = selectedAddress.detail;
			}
		},

		methods: {
			initiateWechatPayment(payParams) {
				wx.config({
					appId: payParams.appId,
					timestamp: payParams.timeStamp,
					nonceStr: payParams.nonceStr,
					signature: payParams.paySign,
					jsApiList: ["chooseWXPay"]
				});

				wx.ready(() => {
					wx.chooseWXPay({
						timestamp: payParams.timeStamp,
						nonceStr: payParams.nonceStr,
						package: payParams.package,
						signType: payParams.signType,
						paySign: payParams.paySign,
						success: (res) => {
							console.log("支付成功", res);
							uni.showModal({
								title: "恭喜您升级成功"
							});
							setTimeout(() => uni.switchTab({
								url: "/pages/my/index"
							}), 2000);
						},
						fail: (err) => {
							console.error("支付失败", err);
							uni.showToast({
								title: "支付失败，请重试",
								icon: "none"
							});
						}
					});
				});
				wx.error((err) => {
					console.error("微信支付 SDK 配置错误", err);
					uni.showToast({
						title: "微信支付初始化失败，请重试",
						icon: "none"
					});
				});
			},

			handlePayment(wxpay) {
				wx.config({
					appId: "wxb1053ee7316c95e8",
					timestamp: wxpay.timeStamp,
					nonceStr: wxpay.nonceStr,
					signature: wxpay.paySign,
					jsApiList: ["chooseWXPay"],
				});
				wx.ready(() => {
					wx.chooseWXPay({
						timestamp: wxpay.timeStamp,
						nonceStr: wxpay.nonceStr,
						package: wxpay.package,
						signType: "MD5",
						paySign: wxpay.paySign,
						success: () => {
							uni.showModal({
								title: "恭喜您升级成功"
							});
							// 2s后跳转首页
							setTimeout(() => uni.switchTab({
								url: "/pages/my/index"
							}), 2000);
							// 2s后跳转优惠券页面
							// setTimeout(() => uni.navigateTo({
							// 	url: "/pages/coupon/index?payMoney=" + this.goodsInfo.money
							// }), 2000);
						},
						fail: () => uni.showToast({
							title: "支付失败",
							icon: "none"
						}),
					});
				});
			},
			openVip() {


				if (!this.form.orderSN || !this.form.name || !this.form.phone || !this.form.detail) {
					return uni.showToast({
						title: "请填写完整信息",
						icon: "none"
					});
				}
				this.form.amount = this.goodsInfo.money;
				// this.form.goods_id = this.id;
				this.form.pname = this.goodsInfo.name;
				// console.log(this.form.pname)
				shop.userlevel(this.form).then((res) => {
					// console.log(res);
					if (res.code === 0) {
						return uni.showToast({
							title: res.msg
						});
					}
					if (this.form.pay_type == 2) {
						uni.showModal({
							title: "恭喜您升级成功"
						});
						// 2s后跳转首页
						setTimeout(() => uni.switchTab({
							url: "/pages/my/index"
						}), 2000);
					} else if (this.form.pay_type == 3) {
						console.log(res.data);
						if (res.code === 1) {
							window.location.href = res.data.url;
						}
					} else {
						// this.handlePayment(res.data.pay);

						// 微信支付参数
						const payParams = res.data.pay;
						console.log("payParams:" + payParams);
						// 调用微信支付
						this.initiateWechatPayment(payParams);
						// // 调用微信支付
						// uni.requestPayment({
						// 	provider: 'wxpay',
						// 	orderInfo: {
						// 		appId: payParams.appId,
						// 		timeStamp: payParams.timeStamp,
						// 		nonceStr: payParams.nonceStr,
						// 		package: payParams.package,
						// 		signType: payParams.signType,
						// 		paySign: payParams.paySign
						// 	},
						// 	success: (paymentRes) => {
						// 		// 支付成功后的回调
						// 		console.log('支付成功', paymentRes);
						// 		uni.showModal({
						// 			title: "恭喜您升级成功"
						// 		});
						// 		// 2s后跳转首页
						// 		setTimeout(() => uni.switchTab({
						// 			url: "/pages/my/index"
						// 		}), 2000);
						// 	},
						// 	fail: (paymentErr) => {
						// 		// 支付失败后的回调
						// 		console.log('支付失败', paymentErr);
						// 		uni.showToast({
						// 			title: '支付失败，请重试',
						// 			icon: 'none'
						// 		});
						// 	}
						// });
					}
				});

			},
			radioChange(evt) {
				this.form.pay_type = evt.target.value;
			},
			getWechatCode() {
				if (isWechat) {
					let appid = "wxb1053ee7316c95e8"; //微信APPid
					let code = this.getUrlCode().code; //是否存在code
					let local = window.location.href;
					if (code == null || code === "") {
						//不存在就打开上面的地址进行授权
						window.location.href =
							"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
							appid +
							"&redirect_uri=" +
							encodeURIComponent(local) +
							"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
					} else {
						this.code = code;
						// alert(this.code)
						this.getCode()
					}
				}
			},
			async getCode() {
				shop.getOpenid({
					code: this.code
				}).then(res => {
					if (res.code == 1) {
						this.disabled = true;
						this.loading = false;
						// this.toast(res.msg);
						// window.location.href = res.data
						// this.status = res.msg;
						console.log('添加成功');
						// this.goBack();
					} else {
						this.loading = false
						// this.toast(res.msg);
					}
				})
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				console.log(url)
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				console.log(theRequest);
				return theRequest;
			},
			chooseAddress() {
				// 添加type参数表示是选择地址模式
				uni.navigateTo({
					url: "/pages/my/shop/address?type=select" // 增加type参数
				});
			},


			increaseQuantity() {
				this.quantity++;
			},
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},
			// async findGoodsInfo() {
			// 	await banlance.getProductDetail({
			// 		id: this.id
			// 	}).then(res => {
			// 		if (res.code == 1) {
			// 			this.goodsInfo = res.data;
			// 			// this.form.name = res.data.user_name || "";
			// 			// this.form.phone = res.data.user_phone || "";
			// 			// this.form.region = res.data.region || [];
			// 			// this.form.detail = res.data.detail || "";
			// 		}
			// 	});
			// },
			submitOrder() {
				// 订单提交逻辑
				console.log("提交订单", this.goodsInfo, this.quantity);
			}
		}
	};
</script>

<style lang="less" scoped>
	/* 用户信息部分样式 */
	.order-user-info {
		width: 100%;
		background-color: #fff;
		height: 180rpx;
		display: flex;
		align-items: center;
		padding: 0 40rpx;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);

		.address-icon {
			width: 55rpx;
			height: 55rpx;
		}

		.user-info {
			color: #6f6f6f;
			width: 90%;
			padding-left: 20rpx;

			.user {
				padding-bottom: 4rpx;

				.name {
					margin-right: 40rpx;
					font-weight: bold;
				}
			}

			.address {
				font-size: 24rpx;
			}
		}
	}

	/* 订单信息部分样式 */
	.order-info-one {
		width: 100%;
		background: #fff;
	}

	.tab-content-item {
		width: 95%;
		height: auto;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin: auto;
		margin-top: 20rpx;

		.tab-center {
			width: 100%;
			margin: auto;

			.shop-info {
				display: flex;
				justify-content: space-between;
				padding: 20rpx 0;

				.shop-info-image {
					width: 140rpx;
					height: 140rpx;
					border-radius: 10rpx;
				}

				.shop-info-content {
					width: 77%;

					.info-content-title,
					.info-content {
						display: flex;
						width: 100%;
						justify-content: space-between;
					}

					.info-content {
						color: #bfbfbf;
						font-size: 24rpx;
						padding-top: 10rpx;
					}
				}
			}

			.pay-money {
				text-align: right;
				font-weight: bold;
				color: #f76e00;
			}
		}

		.buy-count {
			padding: 20rpx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.count-title {
				font-size: 36rpx;
			}

			.edit-count {
				display: flex;

				.minus,
				.plus {
					width: 70rpx;
					height: 70rpx;
					border: 2rpx solid #bfbfbf;
					text-align: center;
					cursor: pointer;
					font-size: 32rpx;
					transition: background-color 0.3s ease;
					display: flex;
					justify-content: center;
					align-items: center;

					&:hover {
						background-color: #f5f5f5;
					}
				}

				.quantity {
					width: 70rpx;
					height: 70rpx;
					text-align: center;
					line-height: 70rpx;
					font-size: 32rpx;
				}
			}
		}


	}

	.order-info-two {
		width: 100%;
		margin-top: 20rpx;
		background-color: #fff;
		padding: 20rpx 30rpx;

		.order-info-content {
			padding-bottom: 40rpx;
			border-bottom: 2rpx solid #eaeaea;

			.item {
				padding: 10rpx 0;
				display: flex;
				justify-content: space-between;
				color: #6f6f6f;
			}
		}

		.all-count {
			display: flex;
			justify-content: flex-end;
			padding: 30rpx 0 15rpx 0;
			align-items: center;
			color: #6f6f6f;

			.price {
				color: #f76e00;
				font-size: 36rpx;
			}
		}
	}

	.order-status-box {
		margin-top: 40rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 40rpx 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

		.status-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;

			.status-icon {
				width: 120rpx;
				height: 120rpx;
				margin-bottom: 30rpx;
			}

			.status-text {
				font-size: 36rpx;
				color: #09bb07;
				font-weight: 600;
				margin-bottom: 20rpx;
			}

			.status-tips {
				font-size: 28rpx;
				color: #666;
				line-height: 1.6;
			}
		}
	}

	.login-form-btn {
		width: 50%;
		background: linear-gradient(90deg, rgba(254, 176, 122, 1) 35%, rgba(242, 171, 235, 1) 100%);
		justify-content: center;
		color: #fff;
		border-radius: 20rpx;
		height: 96rpx;
		display: flex;
		align-items: center;
		margin: auto;
		margin-top: 40rpx;
	}
</style>